package com.zx.tv.service;

import java.io.File;
import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.zx.tv.R;

public class MusicReceiverService extends Service {

	private MediaPlayer mediaPlayer;
	private static final String savePath = "/sdcard/newpai/";
	private String savePath_down = "music/";
	private String mSaveName = "newpaitv.mp3";
	private String mSaveFileName = savePath + savePath_down + mSaveName;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override  
    public void onCreate() {  
		mediaPlayer = null;
        if (mediaPlayer == null) { 
        	if(new File(mSaveFileName).exists()){
        		mediaPlayer = new MediaPlayer();
        		try{
        			mediaPlayer.setDataSource(mSaveFileName);
        			mediaPlayer.prepare();
        		}catch(Exception e){
        			
        		}
        		
        	}else{
        		mediaPlayer = MediaPlayer.create(this, R.raw.heihei);  
        	}
            
            mediaPlayer.setLooping(true);  
        }  
    }	@Override
	public void onDestroy() {
    	super.onDestroy();
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
		}
	}

	@Override
	public void onStart(Intent intent, int startId) {
		if (intent != null) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				int op = bundle.getInt("op");
				switch (op) {
				case 1:
					play();
					break;
				case 2:
					stop();
					break;
				case 3:
					pause();
					break;
				}
			}
		}
	}

	public void play() {
		if (!mediaPlayer.isPlaying()) {
			try {
				mediaPlayer.start();
			} catch (Exception e) {

			}

		}
	}

	public void pause() {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
		}
	}

	public void stop() {
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			try {
				mediaPlayer.prepare(); // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}